import type { ExcelColumnConfig } from '@/types/hmi/ExcelColumnConfig'
import { computed, type ComputedRef, type Ref, ref } from 'vue'
import cloneUtil from '@/types/utils/CloneUtil'

export interface ExcelImportOptions {
  defaultOptions: ExcelColumnConfig[]
}

export interface TableColumn {
  key: string,
  dataKey: string,
  title: string,
  width?: number | string
}

const emptyExcelColumnConfig: ExcelColumnConfig = { key: '', label: '', field: undefined, labelEditable: true }

export interface ExcelImportHandler {
  configs: Ref<ExcelColumnConfig[]>,
  addConfig: (index?: number) => void,
  columns: ComputedRef<TableColumn[]>
  revertDefault: () => void

  [key: string]: any
}

function useExcelImport(options: ExcelImportOptions): ExcelImportHandler {
  const configs: Ref<ExcelColumnConfig[]> = ref<ExcelColumnConfig[]>(cloneUtil.clone(options.defaultOptions))

  const revertDefault = () => {
    configs.value = cloneUtil.clone(options.defaultOptions)
  }

  const columns: ComputedRef<TableColumn[]> = computed((): TableColumn[] => {
    if (!configs.value || configs.value.length <= 0) {
      return []
    }

    const length: number = configs.value.length
    const width: string = `${(100 / length).toFixed(2)}%`

    return configs.value.map((config: ExcelColumnConfig): TableColumn => {
      const uniqueKey: string = config.field || config.key
      return { key: uniqueKey, dataKey: uniqueKey, title: config.label, width }
    })
  })

  const addConfig = (index: number | undefined = undefined) => {
    if (!index || index < 0 || configs.value.length >= index) {
      configs.value.push({ ...emptyExcelColumnConfig })
      return
    }

    configs.value[index] = { ...emptyExcelColumnConfig }
  }

  return { configs, addConfig, columns, revertDefault }
}

export default useExcelImport